/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.login;

import com.codemagi.login.model.*;
import com.codemagi.util.Utils;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;

/**
 * Filters incoming requests to check for a logged in user.
 *
 * Incoming requests will only be allowed if the the user is authenticated.
 * All other requests will be forwarded to /login/index.jsp
 *
 * @todo   Make the forward URL configurable
 */
public final class LoginFilter implements Filter {

    //setup logging
    Logger log = Logger.getLogger(this.getClass());

    private FilterConfig config = null;

    public void init(FilterConfig config) 
	throws ServletException {

	this.config = config;

	log.info("com.codemagi.login.LoginFilter -init");
    }


    public void destroy() {
	this.config = null;
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
	throws ServletException, IOException {

	HttpServletRequest req = (HttpServletRequest)request;

	HttpSession session = req.getSession();

	IUser user = (IUser)session.getAttribute("user");

	if ( user == null || !user.isAuthenticated() ) {

	    String queryString = req.getQueryString();
	    String nextPage = req.getRequestURI() + Utils.noNulls(queryString, "?" + queryString);
	    log.debug("NON-AUTHENTICATED REQUEST FOR: " + nextPage);
	    req.setAttribute("nextPage", nextPage);

	    RequestDispatcher dispatcher = config.getServletContext().getRequestDispatcher(LoginController.VIEW_LOGIN);
	    dispatcher.forward(request, response);
	    return;

	} else {
	    chain.doFilter(request, response);
	}

    }
}
